package com.sense.kukoo.biz_main.view

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayoutMediator
import com.sense.kukoo.biz_explore.view.Explore2Fragment
import com.sense.kukoo.biz_library.view.LibraryFragment
import com.sense.kukoo.biz_main.vm.MainViewModel
import com.sense.kukoo.common.wiget.adapter.CommonPagerAdapter
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.biz_main.R
import com.sense.kukoo.biz_main.databinding.MainActivityMainBinding
import com.sense.kukoo.biz_me.view.MeFragment
import com.sense.kukoo.common.anim.BottomPlayerAnimHelper
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.event.MainPageEvent
import com.sense.kukoo.common.event.MessageCountChangedEvent
import com.sense.kukoo.common.event.TabChangedEvent
import com.sense.kukoo.common.listener.OnScrollYChangedListener
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.lib_logger.LoggerManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ROUTE_MAIN_MODULE_MAIN_ACTIVITY)
class MainActivity : BaseMvvmActivity<MainViewModel, MainActivityMainBinding>() {

    private val TAG: String = javaClass.simpleName

    private lateinit var mMainPagerAdapter: CommonPagerAdapter
    private lateinit var mExploreFragment: Explore2Fragment
    private lateinit var mLibraryFragment:LibraryFragment
    private lateinit var mMeFragment:MeFragment

    private val mBottomPlayerAnimHelper = BottomPlayerAnimHelper()
    private var mCurrentTabPosition = 0

    override fun getLayoutId(): Int = R.layout.main_activity_main

    override fun getViewModelClass(): Class<MainViewModel> = MainViewModel::class.java

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.viewModel = mViewModel
    }

    override fun initView() {
        mMainPagerAdapter = CommonPagerAdapter(this, initFragments())
        mBinding.viewPager.adapter = mMainPagerAdapter
        mBinding.viewPager.isUserInputEnabled = false
        //
        val titles = resources.getStringArray(com.sense.kukoo.common_i18n.R.array.main_channel)
        val mIconNol = intArrayOf(
                com.sense.kukoo.common_design.R.drawable.design_icon_tabbar_home_off_28dp,
                com.sense.kukoo.common_design.R.drawable.design_icon_tabbar_library_off_28dp,
                com.sense.kukoo.common_design.R.drawable.design_icon_tabbar_me_off_28dp
        )
        val mIconSel = intArrayOf(
                com.sense.kukoo.common_design.R.drawable.design_icon_tabbar_home_on_28dp,
                com.sense.kukoo.common_design.R.drawable.design_icon_tabbar_library_on_28dp,
                com.sense.kukoo.common_design.R.drawable.design_icon_tabbar_me_on_28dp
        )
        mBinding.tabs.init(titles, mIconSel, mIconNol)
        TabLayoutMediator(mBinding.tabs, mBinding.viewPager) { tab, position ->
            mBinding.tabs.setTab(tab, position)
        }.attach()

        mBinding.tabs.setOnTabListener {
            LoggerManager.d(TAG,"select tab position=${it}")

            if(it == 1){
                mBinding.tabs.setFollowTabReddot(false)
            }
            if(it == 1 || it == 2){
                //检测是否登陆
                if (!BottomLoginDialog.autoCheckAndLogin(this)) {
                    mBinding.viewPager.setCurrentItem(mCurrentTabPosition, false)
                    return@setOnTabListener
                }
            }
            mCurrentTabPosition = it
            //
            EventBus.getDefault().post(TabChangedEvent(it, -1))
        }
        //
        initMusicPlayer()
        //
        mViewModel.registerPush()
    }

    private fun encodeDeepLink(){
        val deeplink = Repo.link.getAndRemove()
        LoggerManager.d(TAG, "encodeDeepLink deeplink=${deeplink}")
        deeplink?.let {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, it)
                .navigation()
        }
    }

    override fun onResume() {
        super.onResume()
        encodeDeepLink()
    }

    override fun responseVM(action: Int) {}

    private fun initFragments(): List<Fragment> {
        mExploreFragment = Explore2Fragment.newInstance()
        mExploreFragment.setOnScrollYChangedListener(mOnScrollYChangedListener)
        mLibraryFragment = LibraryFragment.newInstance()
        mLibraryFragment.setOnScrollYChangedListener(mOnScrollYChangedListener)
        mMeFragment = MeFragment.newInstance()
        mMeFragment.setOnScrollYChangedListener(mOnScrollYChangedListener)
        val array = ArrayList<Fragment>(3)
        array.add(mExploreFragment)
        array.add(mLibraryFragment)
        array.add(mMeFragment)
        return array
    }

    private val mOnScrollYChangedListener = object : OnScrollYChangedListener {
        override fun onChanged(mainPosition: Int, explorePosition: Int, dy: Int, scrollState:Int) {
            //LoggerManager.e(TAG, "mainPosition=${mainPosition}, explorePosition=${explorePosition}, dy=${dy}")
            mBottomPlayerAnimHelper.dispatchScrollEvent(dy, scrollState)
        }
    }

    private fun initMusicPlayer(){
        mBottomPlayerAnimHelper.setPlayerView(mBinding.musicPlayer)
        //
        mBinding.musicPlayer.alpha = 0F
        mBinding.musicPlayer.animate()
            .alpha(1F)
            .setDuration(400L)
            .withEndAction {
                val maxTranslationY = mBinding.musicPlayer.height.toFloat() + ApplicationContext.dp2px(16F)
                mBottomPlayerAnimHelper.setMaxTranslationY(maxTranslationY)
                LoggerManager.d(TAG, "maxTranslationY=${maxTranslationY}")
            }
            .start()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: TabChangedEvent) {
        mBottomPlayerAnimHelper.animateToShow()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MainPageEvent) {
        mBinding.viewPager.setCurrentItem(event.position,false)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        mViewModel.registerPush()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageCountChangedEvent) {
        if (event.data.isFollowLight()) {
            mBinding.tabs.setFollowTabReddot(true)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}